import os
import logging

from agent.common.system import sysCommand
from agent.feature.base import Feature
from agent.common.config import Config

'''
Feature: erdma
Domain: net
'''

logger = logging.getLogger('common')

class ERDMA(Feature):
    __domain__ = "net"
    __feature__ = "erdma"
    
    def __init__(self) -> None:
        """ Check available of this feature, 
        
        Raises:
            Exception: feature file do not exists
        """
        super().__init__(self.__domain__, self.__feature__)
        
        self.erdma_script = os.path.join(Config.SCRIPTS_PATH, "erdma.sh")
        assert os.path.exists(self.erdma_script)
        
        try:
            sysCommand("{} hasERDMA".format(self.erdma_script), log = True)
        except Exception as e:
            logger.info("eRDMA unavailable: {}".format(e))
            raise
    
    def set_value(self, value):
        """ set feature value

        Args:
            value (_type_): _description_
        """
        assert value in ['on', 'off']
        sysCommand("{} toggleERDMA {}".format(self.erdma_script, value), log = True)
    
    def get_value(self):
        """ read current parameter value

        Returns:
            _type_: _description_
        """
        return sysCommand("{} isERDMA".format(self.erdma_script))
    
    # * By default, the backup() function uses the get_value() function to read the current parameter value
    # * and saves it in a backup file ( in Config.BACKUP_PATH, named as 'net_erdma.json' ). 
    # * The rollback() function reads the backup file and uses the set_value() function to roll back the parameter value. 
    # * If the backup/rollback functions require additional logic, they can be overwritten here.
    
    # def rollback(self):
    #     pass
    
    # def backup(self):
    #     pass


if __name__ == "__main__":
    # * Unit Test Code
    # instantiation
    handler = ERDMA()
    handler.backup()
    # setting parameter value
    handler.set_value("on")
    assert handler.get_value() == "on"

    handler.set_value("off")
    assert handler.get_value() == "off"

    # re-setting current parameter value
    handler.rollback()
